package consumer

import (
	"easyShop/core/config"
	"github.com/streadway/amqp"
	"log"
)

func UpdateProductToEs() error {
	uri := config.GetConfig("rabbit.uri").(string)
	exchange := config.GetConfig("app_name").(string)
	queueName := "product_update_event"

	// 建立连接
	connection, err := amqp.Dial(uri)
	if err != nil {
		log.Println("Failed to connect to RabbitMQ:", err.Error())
		return err
	}

	defer connection.Close()
	// 创建一个Channel
	channel, err := connection.Channel()
	if err != nil {
		log.Println("Failed to open a channel:", err.Error())
		return err
	}
	defer channel.Close()

	// 声明一个队列
	queue, err := channel.QueueDeclare(
		queueName, // name
		true,      // durable
		false,     // delete when usused
		false,     // exclusive
		false,     // no-wait
		nil,       // arguments
	)
	if err != nil {
		log.Println("Failed to declare a queue:", err.Error())
		return err
	}

	// 注册消费者
	msgs, err := channel.Consume(
		queue.Name, // queue
		exchange,   // 标签
		true,       // auto-ack
		false,      // exclusive
		false,      // no-local
		false,      // no-wait
		nil,        // args
	)

	if err != nil {
		log.Println("Failed to register a consumer:", err.Error())
		return err
	}

	// 输出消息
	forever := make(chan bool)
	go func() {
		for d := range msgs {
			log.Println(d.Type)
			log.Println(d.MessageId)
			log.Printf("Received a message: %s", d.Body)
		}
	}()

	log.Printf("Waiting for messages. To exit press CTRL+C")
	<-forever

	return nil
}
